<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1, user-scalable=no">
    <!-- <script src="../../lib/vue.js"></script> -->
    <script src="../../lib/vue.min.js"></script>
    <link rel="stylesheet" href="../../lib/vant@2.12.54_lib_index.css">
    <link rel="stylesheet" href="../../styles/vant.css" />
    <script src="../../lib/vant@2.12.54_lib_vant.min.js"></script>
    <script src="../../lib/axios-0.18.0.js"></script>
    <script src="../../http/request.js"></script>
    <script src="../../utils/fileCompress.js"></script>
    <script src="../../utils/toFormData.js"></script>
    <title>代跑跑</title>
    <style>
        .main {
            overflow: scroll;
            height: 85vh;
        }

        .van-tabbar-item__icon {
            font-size: 30px;
        }

        .van-uploader__wrapper {
            flex-wrap: wrap;
        }

        .van-cell.overflow-visible {
            overflow: visible;
            height: 0;
        }

        .van-uploader__upload {
            bottom: 90px;
            left: 0;
        }

        .van-coupon__condition {
            display: none;
        }

        .van-coupon__amount {
            color: var(--van-primary);
        }

        .van-coupon-list__bottom .van-button--danger {
            background-color: var(--van-primary);
            border: 1px solid var(--van-primary);
        }

        .van-coupon-list__list {
            height: calc(60vh - 48px) !important;
        }

        .van-dialog__confirm,
        .van-dialog__confirm:active {
            color: var(--van-primary);
        }
    </style>
</head>

<body>
    <div id="app">
        <van-nav-bar title="帮我取"></van-nav-bar>
        <div class="main">
            <van-form @submit="onSubmit">

                <van-cell-group title="个人信息" inset>

                    <!-- 联系电话 -->
                    <van-field v-model="phone" type="number" required name="phone" label="联系电话：" placeholder="请输入电话号码"
                        :rules="[{ validator:validatorForPhone, required: true, message: '请输入正确的国内电话号码' }]"></van-field>

                    <!-- 账号 -->
                    <van-field v-model="userNumber" type="number" required label="账号：" placeholder="请输入账号"
                        :rules="[{ required: true, message: '请输入账号' }]"></van-field>

                    <!-- 密码 -->
                    <van-field v-model="password" type="text" required label="密码：" placeholder="请输入密码"
                        :rules="[{ required: true, message: '请输入密码' }]"></van-field>

                </van-cell-group>

                <van-cell-group title="课程信息" inset>

                    <!-- 平台/类型 -->
                    <van-field readonly clickable required :value="platform" label="平台/类型：" placeholder="点击选择平台/类型"
                        @click="isShowPicker = true" :rules="[{ required: true, message: '请选择平台/类型' }]">
                    </van-field>

                    <!-- 课程名 -->
                    <van-field v-model="course" required type="text" label="课程名：" placeholder="请输入课程名"
                        :rules="[{ required: true, message: '请输入课程名' }]"></van-field>

                    <!-- 优惠券单元格 -->
                    <van-coupon-cell :coupons="coupons" :chosen-coupon="chosenCoupon"
                        @click="showCouponList"></van-coupon-cell>

                    <!-- 价格 -->
                    <van-field name="amount" label="价格：">
                        <template #input>
                            <span v-if="isUseDiscount" style="color: red;">
                                ￥ {{discountAmount.toFixed(2)}}&nbsp;
                            </span>
                            <del v-if="isUseDiscount" style="color: red;">
                                <span style="color: #323233;">￥ {{amount.toFixed(2)}}</span>
                            </del>
                            <span v-if="!isUseDiscount" style="color: #323233;">￥ {{amount.toFixed(2)}}</span>
                        </template>
                    </van-field>

                </van-cell-group>

                <!-- 提交按钮 -->
                <div style="margin: 16px;">
                    <van-button round block :loading="isLoading" type="primary" native-type="submit">
                        帮我取
                    </van-button>
                </div>

            </van-form>

            <!-- 平台/类型弹出层  -->
            <van-popup v-model="isShowPicker" position="bottom">
                <van-picker title="选择平台/类型" show-toolbar :columns="platformList" @confirm="getPlatform"
                    @cancel="isShowPicker = false"></van-picker>
            </van-popup>

            <!-- 优惠券列表弹出层 -->
            <van-popup v-model="isShowCouponList" round position="bottom" style="height: 60vh; padding-top: 4px;">
                <van-coupon-list :coupons="coupons" :show-exchange-bar="false" :chosen-coupon="chosenCoupon"
                    :disabled-coupons="disCoupons" @change="changeCoupon">
                </van-coupon-list>
            </van-popup>

        </div>

        <!-- 底层标签页 -->
        <van-tabbar class="tabbar" v-model="active" @change="onChange">
            <van-tabbar-item icon="wap-home" name="home">主页</van-tabbar-item>
            <van-tabbar-item icon="shop" name="information">商家</van-tabbar-item>
            <van-tabbar-item icon="thumb-circle" name="distribute">下单</van-tabbar-item>
            <van-tabbar-item icon="bars" name="order">订单</van-tabbar-item>
            <van-tabbar-item icon="manager" name="personalCenter">我的</van-tabbar-item>
        </van-tabbar>
    </div>
</body>
<script>
    var APPID = "wx576478355cd34bb0"
    new Vue({
        el: "#app",
        data() {
            return {
                isPayVersion: true, // 是否开启支付版本
                phone: '', // 联系电话
                userNumber: '', // 账号
                password: '', // 密码
                platform: '', // 平台或类型
                productId: 0, // 商品 id
                course: '', // 课程名
                amount: 2.99, // 悬赏
                isUseDiscount: false, // 是否使用折扣
                isShowPicker: false, // 是否显示平台/类型的弹出层
                isShowCouponList: false, // 是否显示优惠券列表的弹出层 
                active: 'distribute', // 控制标签栏的显示
                isLoading: false, // 提交按钮是否禁用  
                chosenCoupon: -1, // 默认选择的优惠券
                coupons: [], // 可用优惠券列表
                disCoupons: [], // 不可用优惠券列表
                platformList: [
                    {
                        text: '学习通视频+章测 2.99元',
                        value: 2.99,
                        id: 3
                    },
                    {
                        text: '学习通考试 1.99元',
                        value: 1.99,
                        id: 4
                    },
                    {
                        text: '智慧树视频+章测 3.99元',
                        value: 3.99,
                        id: 5
                    },
                    {
                        text: '智慧树考试 2.50元',
                        value: 2.50,
                        id: 6
                    }
                ]
            }
        },
        methods: {
            // 联系方式表单校验
            validatorForPhone(val) {
                return /^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(val)
            },
            // 获取平台/类型信息
            getPlatform(item) {
                this.isShowPicker = false
                this.platform = item.text
                this.amount = item.value
                this.productId = item.id
            },
            // 展示优惠券列表
            showCouponList() {
                this.isShowCouponList = true
                if (this.chosenCoupon === -1) {
                    setTimeout(() => {
                        const inputs = document.querySelectorAll('.van-checkbox__icon .van-icon.van-icon-success')
                        for (const item of inputs) {
                            item.style.borderColor = '#c8c9cc'
                            item.style.backgroundColor = '#fff'
                        }
                    }, 1)
                }
            },
            // 切换优惠券
            changeCoupon(index) {
                this.isShowCouponList = false
                if (index !== -1) {
                    setTimeout(() => {
                        const inputs = document.querySelectorAll('.van-checkbox__icon .van-icon.van-icon-success')
                        inputs[index].style.borderColor = '#2ED0DF'
                        inputs[index].style.backgroundColor = '#2ED0DF'
                    }, 1)
                }
                this.chosenCoupon = index
            },
            // Tabbar 跳转其他页面
            onChange(index) {
                if (index === 'home') {
                    location.href = '../../home.html?flag=0'
                } else {
                    location.href = `../../${index}.html`
                }
            },
            // 提交订单
            onSubmit(values) {
                this.$dialog.confirm({
                    message: '是否确认提交订单',
                }).then(async () => {
                    // 订单提交提示信息
                    this.$notify({
                        message: '订单提交中，请稍后~~',
                        color: '#ffffff',
                        background: '#ff976a',
                        duration: 2000,
                    })
                    this.isLoading = true
                    // 调用 toFormData 函数，将值存进 FormData 对象
                    const formData = await toFormData(values)
                    this.isUseDiscount ? formData.set('amount', this.discountAmount) : formData.set('amount', this.amount)
                    formData.append('isUseDiscount', this.isUseDiscount)
                    formData.delete('undefined')
                    formData.append('productId', this.productId) // 增加商品类型 id
                    formData.append('packageInfo', this.packageInfo) // 增加账号信息
                    formData.append('remark', this.remark) // 增加账号信息
                    if (this.isUseDiscount) formData.append('couponId', this.coupons[this.chosenCoupon].couponId)
                    // 调用发单接口
                    axios({
                        method: 'POST',
                        url: '/user/order/distribute',
                        // 设置 请求头 formData 格式
                        headers: {
                            'Content-Type': 'multipart/form-data'
                        },
                        data: formData
                    }).then(res => {
                        if (res.code === 1) {
                            if (this.isPayVersion) {
                                // 支付版本
                                const data = res.data
                                if (typeof WeixinJSBridge == "undefined") {
                                    if (document.addEventListener) {
                                        document.addEventListener('WeixinJSBridgeReady', this.onBridgeReady, false);
                                    } else if (document.attachEvent) {
                                        document.attachEvent('WeixinJSBridgeReady', this.onBridgeReady);
                                        document.attachEvent('onWeixinJSBridgeReady', this.onBridgeReady);
                                    }
                                } else {
                                    WeixinJSBridge.invoke(
                                        'getBrandWCPayRequest', {
                                        "appId": APPID,  //公众号ID，由商户传入
                                        "timeStamp": data.timeStamp, //时间戳，自1970年以来的秒数
                                        "nonceStr": data.nonceStr, //随机串
                                        "package": data.prepayId,
                                        "signType": "RSA", //微信签名方式：
                                        "paySign": data.paySign //微信签名
                                    }, (res) => {
                                        if (res.err_msg === "get_brand_wcpay_request:ok") {
                                            // 使用以上方式判断前端返回,微信团队郑重提示：
                                            //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
                                            this.$notify({
                                                message: '订单支付成功,将在2秒后跳转至订单~~',
                                                color: '#ffffff',
                                                background: '#2ED0DF',
                                                duration: 2000,
                                            })
                                            setTimeout(() => {
                                                location.href = `../../order.html`
                                            }, 2000)
                                        } else {
                                            this.$notify({
                                                message: '订单支付失败,请重新下单，如有疑问请添加客服解决~~',
                                                color: '#ffffff',
                                                background: '#ee0a24',
                                                duration: 2000,
                                            })
                                            this.isLoading = false
                                        }
                                    }
                                    )
                                }
                            } else {
                                // 非支付版本
                                this.$notify({
                                    message: '订单支付成功,将在2秒后跳转至订单~~',
                                    color: '#ffffff',
                                    background: '#2ED0DF',
                                    duration: 2000,
                                })
                                setTimeout(() => {
                                    location.href = `../../order.html`
                                }, 2000)
                            }
                        }
                    })
                }).catch(() => {
                })
            },
        },
        async mounted() {
            const res = await axios({ method: 'GET', url: '/user/user/getDA' })
            this.phone = res.data.phone ? res.data.phone : ''
            res.data.coupons.forEach(item => {
                for (let count = 0; count < item.count; count++) {
                    this.coupons.push(item)
                }
            })
            res.data.disCoupons.forEach(item => {
                for (let count = 0; count < item.count; count++) {
                    this.disCoupons.push(item)
                }
            })
        },
        watch: {
            chosenCoupon(newVal) {
                newVal === -1 ? this.isUseDiscount = false : this.isUseDiscount = true
            }
        },
        computed: {
            discountAmount: {
                get() {
                    return ((this.amount * 100) - this.coupons[this.chosenCoupon].value) / 100
                },
                set() {
                }
            },
            packageInfo: {
                get() {
                    return `${this.userNumber} ${this.password}`
                },
                set() {
                }
            },
            remark: {
                get() {
                    const platforms = this.platform.split(' ')
                    return `${platforms[0]} ${this.course}`
                },
                set() {
                }
            }

        }
    })

</script>

</html>